package com.example.gfbosurfaceview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import androidx.annotation.NonNull;

/**
 * surfaceview是view的子类 常用于更新较快的界面
 * surfaceHolder.Callback Surface的生命周期的回调接口
 * View.OnTouchListener 触摸事件
 * SensorEventListener 传感事件
 */
public class GameView extends SurfaceView implements SurfaceHolder.Callback, View.OnTouchListener, SensorEventListener {

    private SurfaceHolder holder;//SurfaceView的托管类
    private Canvas canvas;//画布
    private Paint paint;//画笔

    private int screenwidth, screenheight;//屏幕尺寸相关参数
    private float x, y, radius = 10;//圆相关参数

    private boolean threadFlag;//线程管理参数
    private long speed = 1;
    private int direction = 1;

    private SensorManager sm;//传感器管理类
    private float[] accelerometerValues = new float[3];//加速度传感数据
    private float[] mangeticFieldValues = new float[3];//地磁传感数据

    public GameView(Context context) {
        super(context);
        holder = getHolder();
        holder.addCallback(this);

        paint = new Paint();
        screenwidth = getResources().getDisplayMetrics().widthPixels;
        screenheight = getResources().getDisplayMetrics().heightPixels;

        x = screenwidth / 2;
        y = screenheight / 2;
        //设置触摸监听
        setOnTouchListener(this);
        //设置传感器
        //三个参数 活动，传感类型，传感器相应方式
        sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
        threadFlag = true;
        new DrawThread().start();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
        threadFlag = false;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        x = motionEvent.getRawX();
        y = motionEvent.getRawY();
        return false;
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        //获取对应的传感数据
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            accelerometerValues = sensorEvent.values;
        }
        if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            mangeticFieldValues = sensorEvent.values;
        }
        //数据处理：矩阵变换
        float[] values = new float[3];
        float[] r = new float[9];

        SensorManager.getRotationMatrix(r, null, accelerometerValues, mangeticFieldValues);
        SensorManager.getOrientation(r, values);
        values[1] = (float) Math.toDegrees(values[1]);
        values[2] = (float) Math.toDegrees(values[2]);
        //移动小球
        if (values[2] > 0 && x < screenwidth) x += 5;//右移
        if (values[2] < 0 && x > 0) x -= 5;//左移
        if (values[1] > 0 && y > 0) y -= 5;//上移
        if (values[1] < 0 && y < screenheight) y += 5;//下移
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    private class DrawThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (threadFlag) {
                long _starttime = System.currentTimeMillis();
                long _endtime = System.currentTimeMillis();

                canvas = holder.lockCanvas();//获取当前画布并锁定
                logic();
                draw();
                holder.unlockCanvasAndPost(canvas);// 释放画布并提交刷新界面


                long _sleeptime = speed * 40 - (_endtime - _starttime);
                if (_sleeptime > 0) {
                    try {
                        Thread.sleep(_sleeptime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void draw() {
        //设置画笔清除和重绘的模式
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        canvas.drawPaint(paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
        //绘制矩形背景
        paint.setColor(Color.WHITE);
        canvas.drawRect(0, 0, screenwidth, screenheight, paint);
        //绘制圆形
        paint.setColor(Color.BLUE);
        canvas.drawCircle(x, y, radius, paint);
    }

    private void logic() {
        radius += direction * 5;
        if (radius > 200 || radius < 10) {
            direction *= -1;
        }
    }
}
